
package com.epam.android.training.app.activities;

import com.epam.android.training.app.R;
import com.epam.android.training.app.db.FeedsDb;
import com.epam.android.training.app.db.entities.FeedItem;
import com.epam.android.training.app.services.RSSHandler;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * News activity. Using custom image for the activity background (see
 * gbrepeat.xml) Shows RSS news (for now without ability to update).
 * 
 * @author Natalie
 */
public class NewsActivity extends ActivityWithMenu implements Runnable {

  private static final String TAG = "newsActivity";

  private FeedsDb db;

  private ListView newsListView;

  private List<FeedItem> feedItems;

  private ProgressDialog pd;

  private final Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
      pd.dismiss();
      newsListView = (ListView) findViewById(R.id.news_list_view);
      View view = getLayoutInflater().inflate(R.layout.list_header, null);
      newsListView.addHeaderView(view, null, false);
      newsListView.setAdapter(new NewsArrayAdapter(getApplicationContext(), R.layout.news_row, feedItems));
      newsListView.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> a, View v, int position, long id) {
          FeedItem item = (FeedItem) a.getAdapter().getItem(position);
          Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(item.getUrl().toExternalForm()));
          startActivity(i);
        }
      });

    }
  };

  @Override
  public void run() {
    feedItems = new ArrayList<FeedItem>();
    try {
      feedItems = getFeedItems();
    } catch (MalformedURLException ex) {
      Log.e(TAG, ex.getMessage());
    }
    handler.sendEmptyMessage(0);
  }

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.news);
    pd = ProgressDialog.show(NewsActivity.this, getString(R.string.progress_dilog_title),
        getString(R.string.progress_dialog_text), true, false);
    Thread thread = new Thread(NewsActivity.this);
    thread.start();

  }

  @Override
  protected void onDestroy() {
    super.onDestroy();
    db.close();
  }

  public class NewsArrayAdapter extends ArrayAdapter<FeedItem> {
    List<FeedItem> feedItem;

    public NewsArrayAdapter(Context context, int textViewResourceId, List<FeedItem> items) {
      super(context, textViewResourceId, items);
      feedItem = items;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
      ViewHolder holder;
      if (convertView == null) {
        LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = vi.inflate(R.layout.news_row, null);
        holder = new ViewHolder();
        holder.setTitle((TextView) convertView.findViewById(R.id.title_line));
        holder.setDate((TextView) convertView.findViewById(R.id.date_line));
        convertView.setTag(holder);
      } else {
        holder = (ViewHolder) convertView.getTag();
      }
      FeedItem feed = feedItem.get(position);
      if (null != feed) {
        holder.getTitle().setText(feed.getTitle());
        holder.getDate().setText(Html.fromHtml("<b>" + feed.getDate() + "</b>"));
      }
      return convertView;
    }

  }

  private List<FeedItem> getFeedItems() throws MalformedURLException {
    db = new FeedsDb(getApplicationContext());
    // get feed items from db, if we have nothing - trying to load feed
    List<FeedItem> list = db.getFeedItems();
    if (list == null || list.isEmpty()) {
      RSSHandler handler = new RSSHandler();
      handler.createFeed(getApplicationContext(), new URL(getApplicationContext().getString(R.string.news_url)), false);
      list = db.getFeedItems();
    }
    return list;
  }

  private static class ViewHolder {
    TextView title;

    TextView date;

    public TextView getTitle() {
      return title;
    }

    public void setTitle(TextView title) {
      this.title = title;
    }

    public TextView getDate() {
      return date;
    }

    public void setDate(TextView date) {
      this.date = date;
    }

  }

}
